package com.wq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wq.common.BaseContext;
import com.wq.common.CustomerException;
import com.wq.common.R;
import com.wq.dto.OrdersDto;
import com.wq.entity.*;
import com.wq.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-24 14:20
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    OrderDetailService orderDetailService;

    @Transactional
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info(orders.toString());
        ordersService.submit(orders);
        return R.success("提交订单成功");
    }

    /**
     * 查看该用户所有订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize) {
        Page<Orders> pageForOrders = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqwForOrders = new LambdaQueryWrapper<>();
        final Long userID = BaseContext.getCurrentID();
        lqwForOrders.eq(Orders::getUserId, userID);
        lqwForOrders.orderByDesc(Orders::getCheckoutTime);
        final Page<Orders> ordersPage = ordersService.page(pageForOrders, lqwForOrders);
        final List<Orders> recordsForOrders = ordersPage.getRecords();
        final List<OrdersDto> ordersDtoList = recordsForOrders.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            final String orderNumber = item.getNumber();
            LambdaQueryWrapper<OrderDetail> lqwForDetails = new LambdaQueryWrapper<>();
            lqwForDetails.eq(OrderDetail::getOrderId, orderNumber);
            final List<OrderDetail> orderDetailList = orderDetailService.list(lqwForDetails);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        Page<OrdersDto> pageForDto = new Page<>();
        BeanUtils.copyProperties(pageForOrders, pageForDto, "records");
        pageForDto.setRecords(ordersDtoList);
        return R.success(pageForDto);
    }

}
